import subprocess
import logging
import datetime

# Configure logging
logging.basicConfig(filename='backup_before_upgrade.log', level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

def log_message(message):
    """Log a message to both console and log file."""
    print(message)
    logging.info(message)

def run_command(command):
    """Run a shell command and handle errors."""
    try:
        result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = result.stdout.decode('utf-8')
        log_message(output)
    except subprocess.CalledProcessError as e:
        error_message = f"Error executing command: {e.cmd}\n{e.stderr.decode('utf-8')}"
        log_message(error_message)
        exit(1)

def create_backup(repo_path, backup_name):
    """Create a backup of the current system state."""
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    backup_ref = f"backup-{backup_name}-{timestamp}"
    log_message(f"Creating backup with reference: {backup_ref}")
    run_command(f"sudo ostree refs --repo={repo_path} --create={backup_ref} {backup_name}")

def main():
    repo_path = "/ostree/repo"
    backup_name = "backup"

    # Create a backup of the current system state
    create_backup(repo_path, backup_name)


if __name__ == "__main__":
    main()

